﻿#include "cadreinfotab.h"
#include "ui_cadreinfotab.h"
#include <QSqlQueryModel>
#include <QSqlRecord>
#include <QDebug>
#include <QSqlQuery>
#include <QMessageBox>
#include <QHash>
#include <QPixmap>
#include <QSqlError>
#include <QFileDialog>
#include <QByteArray>
#include <QCompleter>
#include "cadreutil.h"


CadreInfoTab::CadreInfoTab(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CadreInfoTab)
{
    ui->setupUi(this);
    sexHash.insert("1",QString::fromUtf8("男"));
    sexHash.insert("0",QString::fromUtf8("女"));

    yesnoHash.insert("1",QString::fromUtf8("是"));
    yesnoHash.insert("0",QString::fromUtf8("否"));

}

CadreInfoTab::~CadreInfoTab()
{
    delete ui;
}

void CadreInfoTab::initXinXiTab(QSqlRecord data)
{
    QString idnum = data.value("IDNum").toString();
    setXinxiContent(data);
    // 职称
    QSqlQueryModel *titleModel = new QSqlQueryModel(this);
    titleModel->setQuery(QString("SELECT `TitleType`,`TitleLevel`,`TitleGetTime` FROM Title "
                         "where `IDNum`= %1 "
                         "and `TitleGetTime` = ( SELECT max(`TitleGetTime`) "
                          "FROM Title where `IDNum`= %2 );").arg(idnum,idnum));

    if(titleModel->rowCount()!=0){
        QSqlRecord titledata = titleModel->record(0); //只有一行数据
        ui->titletypeLineEdit->setText(titledata.value("TitleType").toString());
        ui->TitleLevelLineEdit->setText(titledata.value("TitleLevel").toString());
        ui->titlegettime->setText(titledata.value("TitleGetTime").toString());
    }else{
        ui->titletypeLineEdit->clear();
        ui->TitleLevelLineEdit->clear();
        ui->titlegettime->clear();
    }
    // 学历
    QSqlQueryModel *eduModel = new QSqlQueryModel(this);
    QString sqlstring = QString("SELECT  educode.`Education`, degreecd.`Degree`,`School`, "
               "`Major`, `WorkORSchool` FROM Edu "
               "left join EducationCode educode on educode.`EducationID`= Edu.`EduName` "
               "left join DegreeCode degreecd on degreecd.`DegreeID`= Edu.`AcademicDe` "
               "where `IDNum` = %1").arg(idnum);
    eduModel->setQuery(sqlstring);
    int educount = eduModel->rowCount();
    if(educount!=0){
        QStringList degreeList,eduList;
        degreeList << trUtf8("博士") <<trUtf8("硕士")<<trUtf8("学士")<<trUtf8("无");
        eduList<< trUtf8("博士研究生") <<trUtf8("硕士研究生")<<trUtf8("研究生")
               <<trUtf8("大学本科")<<trUtf8("大学专科")<<trUtf8("高中")
               <<trUtf8("技工")<<trUtf8("中等师范")<<trUtf8("中等专科");
        QString eduname,academi;
        // int：record中的序号；int：eduList中的序号；(序号小的则说明学历比较高)
        QHash<int,int> eduHash,degreeHash;
        QHash<int,int> workeduHash,workdegreeHash;
        for(int i=0;i<educount;i++){
            eduname = eduModel->record(i).value("Education").toString();
            academi =  eduModel->record(i).value("Degree").toString();
            if(eduModel->record(i).value("WorkORSchool")==1){
                // 如果有特殊情况不再上述所列，也可取到值
                ui->schooleduname->setText(eduname);
                ui->schoolacademicde->setText(academi);
                ui->schoolmajor->setText(
                            eduModel->record(i).value("School").toString()
                            + "" +eduModel->record(i).value("Major").toString());

                foreach(QString degree, degreeList){
                    if(academi.contains(degree)){
                        int index= degreeList.indexOf(degree);
                        degreeHash[i]= index;
                        break;
                    }
                }
                foreach(QString edu, eduList){
                    if(eduname.contains(edu)){
                        int index= eduList.indexOf(edu);
                        eduHash[i]=index;
                        break;
                    }
                }


            }else if(eduModel->record(i).value("WorkORSchool")==0){
                ui->workeduname->setText(eduname);
                ui->workacademicde->setText(academi);
                ui->workschoolmajor->setText(
                            eduModel->record(i).value("School").toString()
                            + "" +eduModel->record(i).value("Major").toString());
                foreach(QString degree, degreeList){
                    if(academi.contains(degree)){
                        int index= degreeList.indexOf(degree);
                        workdegreeHash[i]= index;
                        break;
                    }
                }
                foreach(QString edu, eduList){
                    if(eduname.contains(edu)){
                        int index= eduList.indexOf(edu);
                        workeduHash[i]=index;
                        break;
                    }
                }
            }
        }
        int eduri=CadreUtil::getMinValueFromHash(eduHash);
        int degreeri=CadreUtil::getMinValueFromHash(degreeHash);
        ui->schooleduname->setText(eduModel->record(eduri).value("Education").toString());
        ui->schoolacademicde->setText(eduModel->record(degreeri).value("Degree").toString());
        // 学校与专业对应最高学历的学校及专业
        ui->schoolmajor->setText(
                    eduModel->record(eduri).value("School").toString()
                    + "" +eduModel->record(eduri).value("Major").toString());

        int weduri=CadreUtil::getMinValueFromHash(workeduHash);
        int wdegreeri=CadreUtil::getMinValueFromHash(workdegreeHash);
        ui->workeduname->setText(eduModel->record(weduri).value("Education").toString());
        ui->workacademicde->setText(eduModel->record(wdegreeri).value("Degree").toString());
        // 学校与专业对应最高学历的学校及专业
        ui->workschoolmajor->setText(
                    eduModel->record(weduri).value("School").toString()
                    + "" +eduModel->record(weduri).value("Major").toString());
     }else{
        ui->schooleduname->clear();
        ui->schoolacademicde->clear();
        ui->schoolmajor->clear();
        ui->workeduname->clear();
        ui->workacademicde->clear();
        ui->workschoolmajor->clear();
    }
    // 单位职务 工作经历表中的单位职务
    QSqlQueryModel *experModel = new QSqlQueryModel(this);
    experModel->setQuery(QString("SELECT `ExperID`, `StartTime`, `EndTime`, `UnitName`, `PostName`, `IDNum` "
                                 "FROM Experience where `IDNum`= %1").arg(idnum));
    if(experModel->rowCount()!=0){
        QStringList unitpost;
        for(int i=0;i<experModel->rowCount();i++){
           QString unit=experModel->record(i).value("UnitName").toString();
           QString post=experModel->record(i).value("PostName").toString();
           if(!unit.isEmpty()||!post.isEmpty()){
               unitpost << unit+" "+post;
           }
        }
        ui->unitpost->setText(unitpost.join(";"));
    }else{
        ui->unitpost->clear();
    }

    // 档案编号
    QSqlQueryModel *fileModel = new QSqlQueryModel(this);
    fileModel->setQuery(QString("SELECT `FileID`,`FileNum` FROM File where `IDNum`= %1").arg(idnum));
    if(fileModel->rowCount()!=0){
        fileid = fileModel->record(0).value("FileID").toInt();
        ui->filenumLineEdit->setText(fileModel->record(0).value("FileNum").toString());
    }else{
        fileid =0;
        ui->filenumLineEdit->clear();
    }


}
void CadreInfoTab::setXinxiContent(QSqlRecord &record)
{
    ui->cadreNameLineEdit->setText(record.value("CadreName").toString());
    ui->usedNameLineEdit->setText(record.value("UsedName").toString());
    QString credTypeID= record.value("CredTypeID").toString();
    credTypeIDHash= initComboBox(ui->credTypeIDComboBox,credTypeID,"CredTypeCode","CredTypeID","CredType");
    ui->idNumLineEdit->setText(record.value("IDNum").toString());
    ui->birthDateEdit->setNullable(true);
    ui->birthDateEdit->setDate(record.value("Birth").toDate());
    ui->joinWorkTimeDateEdit->setNullable(true);
    ui->joinWorkTimeDateEdit ->setDate(record.value("JoinWorkTime").toDate());
    QString sex = record.value("Sex").toString();
    initYNComboBox(ui->sexComboBox,sex,sexHash);
    ui->healthLineEdit->setText(record.value("Health").toString());
    QString nationid = record.value("NationID").toString();
    nationHash =initComboBox(ui->nationComboBox,nationid,"NationCode","Nationid","Nation");
    QString nativeid = record.value("NativePlace").toString();
    nativeHash =initComboBox(ui->nativePlacecomboBox,nativeid,"AdminAreaCode","AdminAreaId","AdminArea");
    ui->birthPlaceLineEdit->setText(record.value("Birthplace").toString());
    ui->growPlaceLineEdit->setText(record.value("GrowPlace").toString());
    QString politicid = record.value("PoliticID").toString();
    politicHash =initComboBox(ui->politicComboBox,politicid,"PoliticCode","PoliticID","Politic");
    ui->partyTimeDateEdit->setNullable(true);
    ui->partyTimeDateEdit->setDate(record.value("PartyTime").toDate());
    QString demoparty = record.value("DemoParty").toString();
    initYNComboBox(ui->DemoPartyIDCombo,demoparty,yesnoHash);
    QString retirechange = record.value("RetireChange").toString();
    initYNComboBox(ui->retireChangeComboBox,retirechange,yesnoHash);
    ui->SpecialityLineEdit->setText(record.value("Speciality").toString());
    QString cadrestatusid = record.value("ManageStatusID").toString();
    cadrestatusHash= initComboBox(ui->CadreStatusIDCombo,cadrestatusid,"ManageStatusCode","ManageStatusID","ManageStatus");
    ui->IdenCateLineEdit->setText(record.value("IdenCate").toString());
    QString threeone = record.value("ThreeOne").toString();
    initYNComboBox(ui->ThreeOneComboBox,threeone,yesnoHash);
    ui->PhoneLineEdit->setText(record.value("Phone").toString());
    QString substratumwork = record.value("SubstratumWork").toString();
    initYNComboBox(ui->SubstratumWorkCombo,substratumwork,yesnoHash);
    QString unitid = record.value("UnitID").toString();
    unitHash=initComboBox(ui->unitComboBox,unitid,"unit","unitid","unitname");
    QString rankid = record.value("RankID").toString();
    rankHash=initComboBox(ui->rankComboBox,rankid,"RankCode","RankID","RankName");
    ui->RankTimeDateEdit->setNullable(true);
    ui->RankTimeDateEdit->setDate(record.value("RankTime").toDate());
    ui->RankSalaryLineEdit->setText(record.value("RankSalary").toString());
    ui->ageLineEdit->setText(QString::number(getAge()));
    QString maritalstatus = record.value("MaritalStatusID").toString();
    maritalstatusHash=initComboBox(ui->maritalStatusComboBox,maritalstatus,"MaritalStatusCode","MaritalStatusID","MaritalStatus");

    // 从数据库拿到照片值，并展示到界面
    QPixmap photo;
    dbphoto = record.value("photo").toByteArray();
    bool load =photo.loadFromData(dbphoto);
    //  ui->photoLabel->setPixmap(photo);
    //  ui->photoLabel->setScaledContents(true);
    // 如果用ui->photoLabel->width(),ui->photoLabel->heigh()初始显示的特别小
    if(load){
        ui->photoLabel->setPixmap(photo.scaled(277, 202,
                                 Qt::KeepAspectRatio,
                                 Qt::SmoothTransformation));
    }else{
        ui->photoLabel->clear();
    }


}
// 初始化下拉框及赋值
// 参数含义：cb:组件名称， valueid:初始值， table:参照表名，
//         fieldid: 参照表里的id字段， fieldvalue: 参照表里的name字段(即组件上的显示字段)

QHash<QString,QString> CadreInfoTab::initComboBox(QComboBox *cb, QString valueid,QString table,
                                      QString fieldid,QString fieldvalue)
{
    QSqlQueryModel *model= new QSqlQueryModel(this);
    QString sql = QString::fromUtf8("select %1,%2 from %3").arg(fieldid,fieldvalue,table);
    model->setQuery(sql);
    int rows = model->rowCount();
    QHash<QString,QString> hash;
    QStringList stringlist;
    for (int row=0;row<rows;row++) {
       QString k = model->record(row).value(fieldid).toString();
       QString v = model->record(row).value(fieldvalue).toString();
       hash.insert(k,v);
       stringlist << v;
    }
    cb->clear(); //不先清空，多次点击后 会加载多次
    cb->addItems(stringlist);
    cb->addItem("");
    cb->setEditable(true);

    int index = cb->findText(hash[valueid]);
    cb->setCurrentIndex(index);
    return hash;

}
// 根据固定值设定下拉框
// cb:组件名称，valueid:初始值， hash:包含初始值的对应hash表
void CadreInfoTab::initYNComboBox(QComboBox *cb,QString valueid,QHash<QString,QString> hash)
{
    cb->clear();
    foreach(QString key,hash.uniqueKeys()){
        cb->addItem(hash[key]);
    }
    cb->addItem("");
    int index;
    index = cb->findText(hash[valueid]);
    cb->setCurrentIndex(index);
}

void CadreInfoTab::clearXinxiContent()
{
    ui->cadreNameLineEdit->clear();
    ui->usedNameLineEdit->clear();
    ui->idNumLineEdit->clear();
    ui->credTypeIDComboBox->setCurrentIndex(-1);
    // 日期控件置空
    ui->birthDateEdit->setNullable(true);  //使用之前都要加上此设置
    ui->birthDateEdit->setDate(QDate());
    ui->joinWorkTimeDateEdit->setNullable(true);
    ui->joinWorkTimeDateEdit->setDate(QDate());
    ui->sexComboBox->setCurrentIndex(-1);
    ui->healthLineEdit->clear();
    ui->nationComboBox->setCurrentIndex(-1);
    ui->nativePlacecomboBox->setCurrentIndex(-1);
    ui->birthPlaceLineEdit->clear();
    ui->growPlaceLineEdit->clear();
    ui->politicComboBox->setCurrentIndex(-1);
    ui->partyTimeDateEdit->setNullable(true);
    ui->partyTimeDateEdit->setDate(QDate());
    ui->DemoPartyIDCombo->setCurrentIndex(-1);
    ui->retireChangeComboBox->setCurrentIndex(-1);
    ui->SpecialityLineEdit->clear();
    ui->CadreStatusIDCombo->setCurrentIndex(-1);
    ui->IdenCateLineEdit->clear();
    ui->ThreeOneComboBox->setCurrentIndex(-1);
    ui->PhoneLineEdit->clear();
    ui->SubstratumWorkCombo->setCurrentIndex(-1);
    ui->unitComboBox->setCurrentIndex(-1);
    ui->rankComboBox->setCurrentIndex(-1);
    ui->RankTimeDateEdit->setNullable(true);
    ui->RankTimeDateEdit->setDate(QDate());
    ui->RankSalaryLineEdit->clear();
    ui->photoLabel->clear();
    ui->ageLineEdit->clear();
    ui->titletypeLineEdit->clear();
    ui->TitleLevelLineEdit->clear();
    ui->titlegettime->clear();
    ui->schooleduname->clear();
    ui->schoolacademicde->clear();
    ui->schoolmajor->clear();
    ui->workeduname->clear();
    ui->workacademicde->clear();
    ui->workschoolmajor->clear();
    ui->unitpost->clear();
    ui->maritalStatusComboBox->setCurrentIndex(-1);
}
// 点击锁定/编辑按钮，设置“信息”界面的可编辑情况
void CadreInfoTab::setEditStatus(bool i)
{ // lineEdit setFocusPolicy;  dateEdit setReadOnly;  comboBox setEnable;
    if(i)
    {
        ui->cadreNameLineEdit->setFocusPolicy(Qt::StrongFocus);
        ui->usedNameLineEdit->setFocusPolicy(Qt::StrongFocus);
        ui->idNumLineEdit->setFocusPolicy(Qt::StrongFocus);
        ui->healthLineEdit->setFocusPolicy(Qt::StrongFocus);
        ui->birthPlaceLineEdit->setFocusPolicy(Qt::StrongFocus);
        ui->growPlaceLineEdit->setFocusPolicy(Qt::StrongFocus);
        ui->SpecialityLineEdit->setFocusPolicy(Qt::StrongFocus);
        ui->IdenCateLineEdit->setFocusPolicy(Qt::StrongFocus);
        ui->PhoneLineEdit->setFocusPolicy(Qt::StrongFocus);
        ui->RankSalaryLineEdit->setFocusPolicy(Qt::StrongFocus);
        ui->photoLabel->setFocusPolicy(Qt::StrongFocus);
        ui->filenumLineEdit->setFocusPolicy(Qt::StrongFocus);
     }else {
        ui->cadreNameLineEdit->setFocusPolicy(Qt::NoFocus);
        ui->usedNameLineEdit->setFocusPolicy(Qt::NoFocus);
        ui->idNumLineEdit->setFocusPolicy(Qt::NoFocus);
        ui->healthLineEdit->setFocusPolicy(Qt::NoFocus);
        ui->birthPlaceLineEdit->setFocusPolicy(Qt::NoFocus);
        ui->growPlaceLineEdit->setFocusPolicy(Qt::NoFocus);
        ui->SpecialityLineEdit->setFocusPolicy(Qt::NoFocus);
        ui->IdenCateLineEdit->setFocusPolicy(Qt::NoFocus);
        ui->PhoneLineEdit->setFocusPolicy(Qt::NoFocus);
        ui->RankSalaryLineEdit->setFocusPolicy(Qt::NoFocus);
        ui->photoLabel->setFocusPolicy(Qt::NoFocus);
        ui->titletypeLineEdit->setFocusPolicy(Qt::NoFocus);
        ui->TitleLevelLineEdit->setFocusPolicy(Qt::NoFocus);
        ui->titlegettime->setFocusPolicy(Qt::NoFocus);
        ui->schooleduname->setFocusPolicy(Qt::NoFocus);
        ui->schoolacademicde->setFocusPolicy(Qt::NoFocus);
        ui->schoolmajor->setFocusPolicy(Qt::NoFocus);
        ui->workeduname->setFocusPolicy(Qt::NoFocus);
        ui->workacademicde->setFocusPolicy(Qt::NoFocus);
        ui->workschoolmajor->setFocusPolicy(Qt::NoFocus);
        ui->unitpost->setFocusPolicy(Qt::NoFocus);
        ui->filenumLineEdit->setFocusPolicy(Qt::NoFocus);
     }
        ui->birthDateEdit->setReadOnly(!i);
        ui->joinWorkTimeDateEdit->setReadOnly(!i);
        ui->partyTimeDateEdit->setReadOnly(!i);
        ui->RankTimeDateEdit->setReadOnly(!i);

        ui->sexComboBox->setEnabled(i);
        ui->nationComboBox->setEnabled(i);
        ui->politicComboBox->setEnabled(i);
        ui->DemoPartyIDCombo->setEnabled(i);
        ui->retireChangeComboBox->setEnabled(i);
        ui->CadreStatusIDCombo->setEnabled(i);
        ui->ThreeOneComboBox->setEnabled(i);
        ui->SubstratumWorkCombo->setEnabled(i);
        ui->unitComboBox->setEnabled(i);
        ui->rankComboBox->setEnabled(i);
        ui->photoPushButton->setEnabled(i);
        ui->photoDelPushButton->setEnabled(i);
        ui->credTypeIDComboBox->setEnabled(i);
        ui->maritalStatusComboBox->setEnabled(i);
        ui->nativePlacecomboBox->setEnabled(i);

}


// 获取表单值
QHash<QString,QString> CadreInfoTab::getValue()
{
    QString cadrename=ui->cadreNameLineEdit->text();
    QString usedname=ui->usedNameLineEdit->text();
    QString idnum=ui->idNumLineEdit->text();
    QString health=ui->healthLineEdit->text();
    QString birthplace=ui->birthPlaceLineEdit->text();
    QString growplace=ui->growPlaceLineEdit->text();
    QString speciality=ui->SpecialityLineEdit->text();
    QString idencate=ui->IdenCateLineEdit->text();
    QString phone=ui->PhoneLineEdit->text();
    QString ranksalary= ui->RankSalaryLineEdit->text();
    QString birth=ui->birthDateEdit->date().toString(); //获取日期
    QString joinworktime=ui->joinWorkTimeDateEdit->date().toString();
    QString partytime=ui->partyTimeDateEdit->date().toString();
    QString ranktime=ui->RankTimeDateEdit->date().toString();
    QString sex=sexHash.key(ui->sexComboBox->currentText()); //获取当前下拉框的文本信息
    QString credTypeID=credTypeIDHash.key(ui->credTypeIDComboBox->currentText());
    QString nationid=nationHash.key(ui->nationComboBox->currentText());
    QString politicid=politicHash.key(ui->politicComboBox->currentText());
    QString demopartyid=yesnoHash.key(ui->DemoPartyIDCombo->currentText());
    QString retirechange=yesnoHash.key(ui->retireChangeComboBox->currentText());
    QString cadrestatusid= cadrestatusHash.key(ui->CadreStatusIDCombo->currentText());
    QString threeone=yesnoHash.key(ui->ThreeOneComboBox->currentText());
    QString substratumwork=yesnoHash.key(ui->SubstratumWorkCombo->currentText());
    QString unitid=unitHash.key(ui->unitComboBox->currentText());
    QString rankid=rankHash.key(ui->rankComboBox->currentText());
    QString maritalstatusid=maritalstatusHash.key(ui->maritalStatusComboBox->currentText());
    QString nativeplace=nativeHash.key(ui->nativePlacecomboBox->currentText());
    QHash<QString,QString> formValues;
    formValues.insert("cadrename",cadrename);
    formValues.insert("usedname",usedname);
    formValues.insert("credtype",credTypeID);
    formValues.insert("idnum",idnum);
    formValues.insert("birth",birth);
    formValues.insert("joinworktime",joinworktime);
    formValues.insert("sex",sex);
    formValues.insert("health",health);
    formValues.insert("nationid",nationid);
    formValues.insert("nativeplace",nativeplace);
    formValues.insert("birthplace",birthplace);
    formValues.insert("growplace",growplace);
    formValues.insert("politicid",politicid);
    formValues.insert("partytime",partytime);
    formValues.insert("demopartyid",demopartyid);
    formValues.insert("retirechange",retirechange);
    formValues.insert("speciality",speciality);
    formValues.insert("cadrestatusid",cadrestatusid);
    formValues.insert("idencate",idencate);
    formValues.insert("threeone",threeone);
    formValues.insert("phone",phone);
    formValues.insert("substratumwork",substratumwork);
    formValues.insert("unitid",unitid);
    formValues.insert("rankid",rankid);
    formValues.insert("ranktime",ranktime);
    formValues.insert("ranksalary",ranksalary);
    formValues.insert("maritalstatusid",maritalstatusid);

    return formValues;
}

// 修改
bool CadreInfoTab::updateOrAddXinxi(QString flag,QString currentPerson)
{
    QHash<QString,QString> vhash = getValue();
    if(vhash["cadrename"].isEmpty() || vhash["idnum"].isEmpty()){
        QMessageBox::information(this,trUtf8("操作提示"),
           trUtf8("名字和证件号码不能为空"),QMessageBox::Yes);
        return false;
    }
    // 身份证先做了位数的校验,为了测试方便；后期可以替换为身份证的有效性校验
    if(ui->credTypeIDComboBox->currentText()==trUtf8("居民身份证")){
        if (vhash["idnum"].length()!=18){
            QMessageBox::information(this,trUtf8("操作提示"),
               trUtf8("身份证号为18位"),QMessageBox::Yes);
            return false;
        }
    }
    QSqlQuery query;
    if(flag=="update"){
        query.prepare("update CadreInfo set CadreName= :name,UsedName=:usedname,"
                      "CredTypeID=:credtype,IDNum=:idnum,Birth=:birth,JoinWorkTime=:joinworktime,Sex=:sex"
                      ",Health=:health,NationID=:nationid,NativePlace=:nativeplace,Birthplace=:birthplace"
                      ",GrowPlace=:growplace,PoliticID=:politicid"
                      ",PartyTime=:partytime,DemoParty=:demopartyid,RetireChange=:retirechange"
                      ",Speciality=:speciality,ManageStatusID=:cadrestatusid,IdenCate=:idencate"
                      ",ThreeOne=:threeone,Phone=:phone,SubstratumWork=:substratumwork,UnitID=:unitid"
                      ",RankID=:rankid,RankTime=:ranktime"
                      ",RankSalary=:ranksalary,Photo=:photo,MaritalStatusID=:maritalstatusid "
                      " where IDNum=:id");
       query.bindValue(":id",currentPerson);
       // 档案编号的处理
       if(fileid==0){
           addFileNum();
       }else{
           updateFileNum();
       }
    }
    if(flag=="add"){
        query.prepare("INSERT INTO CadreInfo VALUES (:cadrename, :usedname, :credtype, :idnum, "
                      ":birth, :joinworktime, :sex, :health, :nationid, :nativeplace, "
                      ":birthplace, :growplace, :politicid, :partytime, :demopartyid, "
                      ":retirechange, :speciality, :cadrestatusid,:idencate, :threeone, "
                      ":phone, :substratumwork, :unitid, :rankid, :ranktime, :ranksalary, "
                      ":photo, :maritalstatusid )");
        // 档案编号的处理
        addFileNum();
    }

    query.bindValue(":name",vhash["cadrename"]);
    query.bindValue(":usedname",vhash["usedname"]);
    query.bindValue(":credtype",vhash["credtype"]);
    query.bindValue(":idnum",vhash["idnum"]);
    query.bindValue(":birth",QDate::fromString(vhash["birth"]));
    query.bindValue(":joinworktime",QDate::fromString(vhash["joinworktime"]));
    query.bindValue(":sex",vhash["sex"]);
    query.bindValue(":health",vhash["health"]);
    query.bindValue(":nationid",vhash["nationid"]);
    query.bindValue(":nativeplace",vhash["nativeplace"]);
    query.bindValue(":birthplace",vhash["birthplace"]);
    query.bindValue(":growplace",vhash["growplace"]);
    query.bindValue(":politicid",vhash["politicid"]);
    query.bindValue(":partytime",QDate::fromString(vhash["partytime"]));
    query.bindValue(":demopartyid",vhash["demopartyid"]);
    query.bindValue(":retirechange",vhash["retirechange"]);
    query.bindValue(":speciality",vhash["speciality"]);
    query.bindValue(":cadrestatusid",vhash["cadrestatusid"]);
    query.bindValue(":idencate",vhash["idencate"]);
    query.bindValue(":threeone",vhash["threeone"]);
    query.bindValue(":phone",vhash["phone"]);
    query.bindValue(":substratumwork",vhash["substratumwork"]);
    query.bindValue(":unitid",vhash["unitid"].toInt());
    query.bindValue(":rankid",vhash["rankid"]);
    query.bindValue(":ranktime",QDate::fromString(vhash["ranktime"]));
    query.bindValue(":ranksalary",vhash["ranksalary"]);
    query.bindValue(":maritalstatusid",vhash["maritalstatusid"]);


    // 获取图片值
    if(OpenFilePath!=""){
       QByteArray photo = getImageValue();
       query.bindValue(":photo",photo); //最新的照片
    } else if( OpenFilePath=="" && flag=="update"){
       query.bindValue(":photo",dbphoto); //原来存的照片
    } else {
        query.bindValue(":photo",QByteArray());
    }

    if(query.exec()){
        setEditStatus(false);
        addPerson = vhash["idnum"];
        OpenFilePath=""; //成功置空
        return true;
    }else{
        OpenFilePath=""; //操作失败置空
        qDebug()<<query.lastError().databaseText();
        qDebug()<<query.lastError().driverText();
        QString info = query.lastError().databaseText();
        if(info.contains("too long")){
            info = QString::fromUtf8("图片太大，请不要超过64K");
        }
        QMessageBox::information(this,trUtf8("操作提示"),
           info,QMessageBox::Yes);
        return false;
    }
}
// 点击"更改"按钮
void CadreInfoTab::on_photoPushButton_clicked()
{
    QString path= QFileDialog::getOpenFileName(
        this,
        "Choose image",
        "",
        "Image Files(*.jpg *.png *.bmp *.pgm *.pbm)");
    if(path!=""){
        OpenFilePath=path;
        QImage img;
        img.load(OpenFilePath);
        ui->photoLabel->setPixmap(QPixmap::fromImage(img)
                                  .scaled(ui->photoLabel->width(), ui->photoLabel->height(),
                                  Qt::KeepAspectRatio,
                                  Qt::SmoothTransformation));
    }

}
// 从本地获取值，准备存入数据库
QByteArray CadreInfoTab:: getImageValue(){
    QFile file(OpenFilePath);
    if(!file.open(QIODevice::ReadOnly))
    {
    qDebug()<<"open failed";
    }
    QByteArray data = file.readAll();
    if(data.isEmpty())
    {
    qDebug()<<"data is empty";
    }
    file.close();
    return data;
}

// 年龄的计算
int CadreInfoTab::getAge()
{
    QDate birthday=ui->birthDateEdit->date();
    int age=0;
    if(birthday!=QDate()){
        QDate current= QDate::currentDate();
        int days =birthday.daysTo(current);
        age = days/365;
    }
    return age;
}

void CadreInfoTab::on_birthDateEdit_editingFinished()
{
    int age=getAge();
    ui->ageLineEdit->setText(QString::number(age));
}

void CadreInfoTab::on_photoDelPushButton_clicked()
{
    if(!dbphoto.isEmpty())  dbphoto = QByteArray();
    OpenFilePath="";
    ui->photoLabel->clear();
}
void CadreInfoTab::addFileNum()
{
   QSqlQuery query;
   query.prepare("INSERT INTO File (`FileNum`, `IDNum`) values (:filenum, :idnum)");
   query.bindValue(":filenum",ui->filenumLineEdit->text());
   query.bindValue(":idnum",ui->idNumLineEdit->text());
   query.exec();
}
void CadreInfoTab::updateFileNum()
{
   QSqlQuery query;
   query.prepare("UPDATE File  SET `FileNum`=:filenum, `IDNum`=:idnum WHERE `FileID`=:fileid;");
   query.bindValue(":filenum",ui->filenumLineEdit->text());
   query.bindValue(":idnum",ui->idNumLineEdit->text());
   query.bindValue(":fileid",fileid);
   if(!query.exec()){
       qDebug()<< query.lastError().text();
   }

}
